<template>
  <div class="data-sync-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <n-button text @click="$router.back()">
        <n-icon :size="20">
          <ArrowBackIcon />
        </n-icon>
      </n-button>
      <h1>数据同步</h1>
    </div>

    <!-- 页面内容 -->
    <div class="page-content">
      <n-space vertical :size="24">
        
        <!-- 匿名用户提示 -->
        <n-alert v-if="isAnonymousUser" type="info" :bordered="false">
          <template #icon>
            <n-icon><InformationCircleIcon /></n-icon>
          </template>
          您当前以游客身份使用，仅可使用本地数据管理功能（导出、导入、清除数据）。
          <router-link to="/login" class="upgrade-link">注册账号</router-link>以解锁完整功能。
        </n-alert>

        <!-- 同步状态 -->
        <n-card v-if="!isAnonymousUser" title="同步状态" :bordered="false">
          <n-space vertical :size="16">
            <div class="status-item">
              <span class="label">同步状态：</span>
              <n-tag :type="syncStatus.isAutoSyncEnabled ? 'success' : 'default'">
                {{ syncStatus.isAutoSyncEnabled ? '自动同步已启用' : '手动同步' }}
              </n-tag>
            </div>

            <div class="status-item">
              <span class="label">最后同步：</span>
              <span class="value">
                {{ syncStatus.lastSyncTime ? formatTime(syncStatus.lastSyncTime) : '从未同步' }}
              </span>
            </div>

            <div class="status-item">
              <span class="label">同步间隔：</span>
              <span class="value">{{ syncStatus.syncInterval }} 分钟</span>
            </div>
          </n-space>
        </n-card>

        <!-- 同步设置 -->
        <n-card v-if="!isAnonymousUser" title="同步设置" :bordered="false">
          <n-form :model="syncSettings" label-placement="left" label-width="120px">
            <n-form-item label="同步模式">
              <n-radio-group v-model:value="syncMode" @update:value="handleSyncModeChange">
                <n-radio value="local">本地存储</n-radio>
                <n-radio value="backend">后端同步</n-radio>
              </n-radio-group>
            </n-form-item>

            <n-form-item label="自动同步">
              <n-switch
                v-model:value="syncSettings.autoSync"
                @update:value="handleAutoSyncChange"
              />
            </n-form-item>

            <n-form-item label="同步间隔" v-if="syncSettings.autoSync">
              <n-select
                v-model:value="syncSettings.syncInterval"
                :options="intervalOptions"
                @update:value="handleIntervalChange"
                style="width: 200px"
              />
            </n-form-item>
          </n-form>
        </n-card>

        <!-- 手动操作 -->
        <n-card v-if="!isAnonymousUser" title="手动操作" :bordered="false">
          <n-space vertical :size="16">
            <n-button
              type="primary"
              :loading="syncing"
              @click="handleManualSync"
              block
            >
              <template #icon>
                <n-icon><SyncIcon /></n-icon>
              </template>
              立即同步
            </n-button>

            <n-button
              @click="handleRestoreFromLocal"
              :loading="restoring"
              block
            >
              <template #icon>
                <n-icon><RestoreIcon /></n-icon>
              </template>
              从本地恢复数据
            </n-button>
          </n-space>
        </n-card>

        <!-- 存储信息 -->
        <n-card title="存储信息" :bordered="false">
          <n-space vertical :size="16">
            <div class="storage-info">
              <div class="storage-item">
                <span class="label">已使用空间：</span>
                <span class="value">{{ formatStorageSize(storageInfo.used) }}</span>
              </div>
              
              <div class="storage-item">
                <span class="label">使用率：</span>
                <span class="value">{{ storageInfo.percentage.toFixed(1) }}%</span>
              </div>
              
              <n-progress 
                :percentage="storageInfo.percentage" 
                :color="getProgressColor(storageInfo.percentage)"
                style="margin-top: 8px"
              />
            </div>
            
            <n-collapse>
              <n-collapse-item title="详细信息" name="details">
                <div class="storage-details">
                  <div v-for="(size, name) in storageInfo.items" :key="name" class="detail-item">
                    <span class="name">{{ getStorageName(name) }}：</span>
                    <span class="size">{{ formatStorageSize(size) }}</span>
                  </div>
                </div>
              </n-collapse-item>
            </n-collapse>
          </n-space>
        </n-card>

        <!-- 数据管理 -->
        <n-card title="数据管理" :bordered="false">
          <n-space vertical :size="16">
            <n-button @click="handleExportData" block>
              <template #icon>
                <n-icon><DownloadIcon /></n-icon>
              </template>
              导出数据
            </n-button>
            
            <n-upload
              :show-file-list="false"
              accept=".json"
              @change="handleImportData"
            >
              <n-button block>
                <template #icon>
                  <n-icon><UploadIcon /></n-icon>
                </template>
                导入数据
              </n-button>
            </n-upload>
            
            <n-popconfirm
              @positive-click="handleClearData"
              positive-text="确认清除"
              negative-text="取消"
            >
              <template #trigger>
                <n-button type="error" block>
                  <template #icon>
                    <n-icon><DeleteIcon /></n-icon>
                  </template>
                  清除本地数据
                </n-button>
              </template>
              确定要清除所有本地数据吗？此操作不可恢复。
            </n-popconfirm>
          </n-space>
        </n-card>

      </n-space>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useMessage } from 'naive-ui'
import {
  ArrowBack as ArrowBackIcon,
  Settings as SyncIcon,
  Home as RestoreIcon,
  Download as DownloadIcon,
  Add as UploadIcon,
  Trash as DeleteIcon,
  InformationCircle as InformationCircleIcon
} from '@vicons/ionicons5'
import { LocalStorageManager, formatStorageSize, type SyncSettings } from '@/utils/localStorage'
import { SyncService } from '@/services/syncService'
import { useEventsStore } from '@/stores/events'
import { useUserStore } from '@/stores/user'

const message = useMessage()
const userStore = useUserStore()

// 判断是否为匿名用户
const isAnonymousUser = computed(() => {
  return userStore.user?.is_anonymous === true
})

// 响应式数据
const syncing = ref(false)
const restoring = ref(false)

// 同步模式
const syncMode = ref<'local' | 'backend'>('local')

// 同步设置
const syncSettings = reactive<SyncSettings>({
  autoSync: false,
  syncInterval: 30
})

// 同步状态
const syncStatus = ref({
  isAutoSyncEnabled: false,
  lastSyncTime: null as string | null,
  isSyncing: false,
  syncInterval: 30
})

// 存储信息
const storageInfo = ref({
  used: 0,
  total: 0,
  percentage: 0,
  items: {} as Record<string, number>
})

// 同步间隔选项
const intervalOptions = [
  { label: '5分钟', value: 5 },
  { label: '15分钟', value: 15 },
  { label: '30分钟', value: 30 },
  { label: '1小时', value: 60 },
  { label: '2小时', value: 120 },
  { label: '6小时', value: 360 },
  { label: '12小时', value: 720 },
  { label: '24小时', value: 1440 }
]

// 初始化数据
onMounted(() => {
  loadSyncSettings()
  loadSyncStatus()
  loadStorageInfo()

  // 加载同步模式
  syncMode.value = SyncService.isBackendSyncEnabled() ? 'backend' : 'local'
})

// 加载同步设置
const loadSyncSettings = () => {
  const settings = LocalStorageManager.getSyncSettings()
  Object.assign(syncSettings, settings)
}

// 加载同步状态
const loadSyncStatus = () => {
  syncStatus.value = SyncService.getSyncStatus()
}

// 加载存储信息
const loadStorageInfo = () => {
  storageInfo.value = LocalStorageManager.getStorageInfo()
}

// 处理同步模式变化
const handleSyncModeChange = (value: 'local' | 'backend') => {
  SyncService.setBackendSyncMode(value === 'backend')
  message.success(`已切换到${value === 'backend' ? '后端同步' : '本地存储'}模式`)

  if (value === 'backend') {
    message.info('后端同步模式需要配置服务器地址，当前为演示模式')
  }
}

// 处理自动同步开关变化
const handleAutoSyncChange = (value: boolean) => {
  const newSettings = { ...syncSettings, autoSync: value }
  SyncService.updateSyncSettings(newSettings)
  loadSyncStatus()
  message.success(value ? '自动同步已启用' : '自动同步已关闭')
}

// 处理同步间隔变化
const handleIntervalChange = (value: number) => {
  const newSettings = { ...syncSettings, syncInterval: value }
  SyncService.updateSyncSettings(newSettings)
  loadSyncStatus()
  message.success(`同步间隔已设置为 ${value} 分钟`)
}

// 手动同步
const handleManualSync = async () => {
  syncing.value = true
  try {
    const result = await SyncService.manualSync()
    if (result.success) {
      message.success(result.message)
    } else {
      message.error(result.message)
    }
    loadSyncStatus()
    loadStorageInfo()
  } catch (error) {
    message.error('同步失败')
  } finally {
    syncing.value = false
  }
}

// 从本地恢复数据
const handleRestoreFromLocal = async () => {
  restoring.value = true
  try {
    const result = await SyncService.restoreFromLocal()
    if (result.success) {
      message.success(result.message)
    } else {
      message.error(result.message)
    }
  } catch (error) {
    message.error('恢复数据失败')
  } finally {
    restoring.value = false
  }
}

// 导出数据
const handleExportData = () => {
  try {
    const data = LocalStorageManager.exportData()
    const blob = new Blob([data], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `todo-calendar-data-${new Date().toISOString().split('T')[0]}.json`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
    message.success('数据导出成功')
  } catch (error) {
    message.error('导出数据失败')
  }
}

// 导入数据
const handleImportData = ({ file }: any) => {
  if (!file.file) return
  
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const jsonData = e.target?.result as string
      LocalStorageManager.importData(jsonData)
      loadStorageInfo()
      message.success('数据导入成功')
    } catch (error) {
      message.error('导入数据失败，请检查文件格式')
    }
  }
  reader.readAsText(file.file)
}

// 清除本地数据
const handleClearData = async () => {
  try {
    console.log('🧹 开始清除本地数据')
    LocalStorageManager.clearAllData()
    console.log('🧹 本地数据已清除')

    // 重新初始化事件数据
    const eventsStore = useEventsStore()
    console.log('🧹 重新初始化事件数据')
    await eventsStore.init()
    console.log('🧹 事件数据初始化完成')

    loadStorageInfo()
    loadSyncStatus()
    message.success('本地数据已清除，已重新加载默认数据')
  } catch (error) {
    console.error('🧹 清除数据失败:', error)
    message.error('清除数据失败')
  }
}

// 格式化时间
const formatTime = (timeString: string) => {
  const date = new Date(timeString)
  return date.toLocaleString('zh-CN')
}

// 获取进度条颜色
const getProgressColor = (percentage: number) => {
  if (percentage < 50) return '#18a058'
  if (percentage < 80) return '#f0a020'
  return '#d03050'
}

// 获取存储项名称
const getStorageName = (key: string) => {
  const nameMap: Record<string, string> = {
    EVENTS: '事件数据',
    EVENT_TYPES: '事件类型',
    DIET_TYPES: '饮食类型',
    SYNC_SETTINGS: '同步设置',
    LAST_SYNC_TIME: '同步时间'
  }
  return nameMap[key] || key
}
</script>

<style scoped>
.data-sync-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid #e0e0e0;
  position: sticky;
  top: 0;
  z-index: 10;
}

.page-header h1 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.page-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-item .label {
  font-weight: 500;
  color: #666;
}

.status-item .value {
  color: #333;
}

.storage-info {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.storage-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.storage-item .label {
  font-weight: 500;
  color: #666;
}

.storage-item .value {
  color: #333;
}

.storage-details {
  padding: 8px 0;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
}

.detail-item .name {
  color: #666;
}

.detail-item .size {
  color: #333;
  font-family: monospace;
}

.upgrade-link {
  color: #18a058;
  text-decoration: none;
  font-weight: 500;
  margin-left: 4px;
}

.upgrade-link:hover {
  text-decoration: underline;
}

@media (max-width: 768px) {
  .page-header {
    padding: 12px 16px;
  }

  .page-content {
    padding: 16px;
  }
}
</style>
